package lang.exception;

import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @Description：
 * @Author：LiDong
 * @Create：2021/3/27
 * @Version：1.0.0
 */
public class TryCatchTest {

    private final Logger logger = LoggerFactory.getLogger(TryCatchTest.class);

    @Test
    public void test1() {
        try {
            logger.info("test messages!");
            throw new MyException("test!");
        } catch (Exception e) {
            logger.info(e.getMessage());
        }
    }

    /**
     * finally 的使用
     */
    @Test
    public void test2() {
        try {
            logger.info("test!");
        } catch (NullPointerException | IllegalArgumentException nullPointerException) {
            logger.info(nullPointerException.getMessage());
        }
    }


    @Test
    public void finallyTest() {
        int num = oneMethod();
        logger.info(String.valueOf(num));
    }

    private int oneMethod() {
        try {
            int i = 4 / 0;
        } catch (Exception e) {
            logger.error("Error Occur:{}", e.getMessage());
        } finally {
            // finally 中一般不做业务逻辑处理，关闭流什么的
        }
        return 4;
    }


    /**
     * 除非上面的代码抛出异常，`finally`中的代码一定会执行，即使上面有`return`语句
     */
    @Test
    public void testFinally() {
        int num = twoMethod();
        logger.info(String.valueOf(num));
    }

    private int twoMethod() {
        try {
            return 3;
        } catch (Exception e) {

        } finally {
            return 4;
        }
    }

    @Test
    public void test3() {
        try {
            String a = null;
            // String str = a.toString();
            method1();
            logger.info(a);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        logger.info("ok");
    }

    private void method1() {
        String a = null;
        String str = a.toString();
    }

    /**
     * try finally finally 代码块总会执行
     */
    @Test
    public void tryFinally() {
        try {
            String a = null;
            String str = a.toString();
            logger.info(str);
        } finally {
            logger.error("finally code ok");
        }
        logger.info("test");
    }

}
